import Vue from "vue";
import router from "./index";
import store from "../store";
import NProgress from "nprogress"; // progress bar
import "nprogress/nprogress.css"; // progress bar style
import { ACCESS_TOKEN } from "@/store/mutation-types";
import { initRouter } from "./routerUtil";
import defaultSettings from "@/config/defaultSettings";

NProgress.configure({ showSpinner: false }); // NProgress Configuration

const whiteList = ["login"]; // no redirect whitelist

router.beforeEach((to, from, next) => {
  NProgress.start(); // start progress bar
  to.meta &&
    typeof to.meta.title !== "undefined" &&
    setDocumentTitle(`${to.meta.title} - ${domTitle}`);
  // 已授权
  if (Vue.ls.get(ACCESS_TOKEN)) {
    if (to.path === "/login") {
      next();
      NProgress.done();
    } else {
      store.dispatch("GetInfo").then(() => {
        initRouter(to, from, next).then(() => {
          const redirect = decodeURIComponent(from.query.redirect || to.path);
          //桌面特殊处理
          if (to.path == defaultSettings.desktopPath || to.path == "/404") {
            next();
          } else {
            if (to.path === redirect) {
              next();
            } else {
              // 跳转到目的路由
              next({ path: redirect });
            }
          }
        });
      });
    }
  } else {
    if (to.path === "/login") {
      next();
    } else if (whiteList.includes(to.name)) {
      // 在免登录白名单，直接进入
      next();
    } else {
      next({
        path: "/login",
        query: { redirect: to.fullPath }
      });
      NProgress.done(); // if current page is login will not trigger afterEach hook, so manually handle it
    }
    NProgress.done();
  }
});

router.afterEach(() => {
  NProgress.done(); // finish progress bar
});

//设置标题
const setDocumentTitle = function(title) {
  document.title = title;
  const ua = navigator.userAgent;
  // eslint-disable-next-line
  const regex = /\bMicroMessenger\/([\d\.]+)/
  if (regex.test(ua) && /ip(hone|od|ad)/i.test(ua)) {
    const i = document.createElement("iframe");
    i.src = "/logo.png";
    i.style.display = "none";
    i.onload = function() {
      setTimeout(function() {
        i.remove();
      }, 9);
    };
    document.body.appendChild(i);
  }
};
const domTitle = process.env.VUE_APP_ProjectName;
